package com.ckf.aliyun.controller;

import com.aliyuncs.utils.StringUtils;
import com.ckf.aliyun.service.SendSmsService;
import io.netty.util.internal.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author: serene
 * @date: 2020/9/24 10:01
 */

@RestController
@CrossOrigin
public class SmsapiController {

    @Autowired
    private SendSmsService sendSmsService;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    /**
     * 短信验证
     * Restful风格 测试路径为：http://localhost:9090/send/电话号码
     * @param phone
     * @return
     */
    @GetMapping("/send/{phone}")
    public String code(@PathVariable("phone") String phone){
        //把号码存到redis中
        String code=redisTemplate.opsForValue().get(phone);

        //判断验证码是否已存在，按照正常的逻辑，验证码相同是不影响的
        if (!StringUtils.isEmpty(code)){
            return phone+ ":" +code+ "已存在，还没过期";
        }

        //自动生成验证码，并且存到redis中
        code= UUID.randomUUID().toString().substring(0,4);
        HashMap<String, Object> param = new HashMap<>();
        param.put("code",code);

        boolean isSend = sendSmsService.send(phone, "模版CODE(SMS_203176825)", param);

        if (isSend){
            redisTemplate.opsForValue().set(phone,code,5,TimeUnit.SECONDS);
            return phone+":" +code+"发送成功";
        }else{
            return "发送失败";
        }


    }
}
